package aiku.numericalcontroloa.Service.Impl;

import aiku.numericalcontroloa.Base.Utils.Result;
import aiku.numericalcontroloa.Base.Utils.StringUtils;
import aiku.numericalcontroloa.Mapper.DieBonusMapper;
import aiku.numericalcontroloa.Mapper.DieBonusinfoMapper;
import aiku.numericalcontroloa.Mapper.DieCustomMapper;
import aiku.numericalcontroloa.Mapper.UserMapper;
import aiku.numericalcontroloa.Mapper.dieOrderReceivablesMapper;
import aiku.numericalcontroloa.Mapper.FinanceManagement.AccountMapper;
import aiku.numericalcontroloa.Model.Dto.DieOrderDto;
import aiku.numericalcontroloa.Model.Entity.DieBonus;
import aiku.numericalcontroloa.Model.Entity.DieBonusinfo;
import aiku.numericalcontroloa.Model.Entity.DieCustom;
import aiku.numericalcontroloa.Model.Entity.User;
import aiku.numericalcontroloa.Model.Entity.dieOrderReceivables;
import aiku.numericalcontroloa.Model.Entity.FinanceManagement.Account;
import aiku.numericalcontroloa.Model.Vo.DieOrderPageVO;
import aiku.numericalcontroloa.Model.Vo.DieOrderStatisticsVo;
import aiku.numericalcontroloa.Model.Vo.DieOrderVo;
import aiku.numericalcontroloa.Service.DieOrderService;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.query.MPJLambdaQueryWrapper;

import aiku.numericalcontroloa.Model.Entity.DieOrder;
import aiku.numericalcontroloa.Model.Entity.DieOrderJoin;
import aiku.numericalcontroloa.Mapper.DieOrderMapper;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.Collator;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author 马
 * @description 针对表【die_order】的数据库操作Service实现
 * @createDate 2024-05-13 16:46:52
 */
@Service
@Slf4j
public class DieOrderServiceImpl extends MPJBaseServiceImpl<DieOrderMapper, DieOrder>
        implements DieOrderService {
    @Autowired
    private DieOrderMapper dieOrderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DieBonusMapper dieBonusMapper;
    @Autowired
    private DieBonusinfoMapper dieBonusinfoMapper;
    @Autowired
    private DieBonusinfoServiceImpl dieBonusinfoService;
    @Autowired
    private dieOrderReceivablesMapper dmapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private DieCustomMapper dieCustomMapper;

    /**
     * 创建订单
     * 
     * @return
     */
    @Override
    public Result createOrder(DieOrderDto dieOrder) {
        if (dieOrder.getNameId() == null && dieOrder.getVersionNumber() == null && dieOrder.getProductName() == null
                && dieOrder.getPrice() == null) {
            return Result.error("缺少参数");
        }
        DieOrder order = new DieOrder();
        BeanUtils.copyProperties(dieOrder, order);
        Map<String, String> map = new HashMap<>();
//        String userid = StpUtil.getLoginId().toString();
//        order.setCompleteOrder(userid);
        if (dieOrderMapper.insert(order) == 1) {
            map.put("id", order.getId());
            return Result.success("创建成功", map);
        } else {
            return Result.error("创建失败");
        }
    }

    /**
     * 修改订单
     * 
     * @param dieOrder
     * @return
     */
    @Override
    public Result updateOrder(DieOrderDto dieOrder) {
        if (dieOrder.getNameId() == null && dieOrder.getVersionNumber() == null && dieOrder.getProductName() == null
                && dieOrder.getPrice() == null) {
            return Result.error("缺少参数");
        }
        String userid = StpUtil.getLoginId().toString();

        DieOrder o = dieOrderMapper.selectById(dieOrder.getId());
        if ((!(o.getCompleteOrder() == null || o.getCompleteOrder().equals("")))
                && !userMapper.selectById(userid).getRoleId().equals("1")) {
            return Result.error("订单已完成，修改权限不足");
        }
        DieOrder order = new DieOrder();
        BeanUtils.copyProperties(dieOrder, order);
        if (dieOrderMapper.updateById(order) == 1) {
            return Result.success("修改成功");
        } else {
            return Result.error("修改失败");
        }
    }

    /**
     * 查询订单信息
     * 
     * @param page
     * @param size
     * @return
     */
    @Override
    public Result getOrderList(DieOrderDto dieOrder) {
        if (dieOrder.getCurrentPage() == null && dieOrder.getPageSize() == null) {
            return Result.error("缺少分页参数");
        }
        // 创建分页对象
        Page<DieOrder> pages = new Page<>(dieOrder.getCurrentPage(), dieOrder.getPageSize());
        LambdaQueryWrapper<DieOrder> queryWrapper = new LambdaQueryWrapper<>();

        if (dieOrder.getNameId() != null) {
            queryWrapper.eq(DieOrder::getNameId, dieOrder.getNameId());
        }
        if (dieOrder.getVersionNumber() != null) {
            queryWrapper.like(DieOrder::getVersionNumber, dieOrder.getVersionNumber());
        }
        if (dieOrder.getProductName() != null) {
            queryWrapper.like(DieOrder::getProductName, dieOrder.getProductName());
        }

        if (dieOrder.getIsSend() != null) {
            queryWrapper.eq(DieOrder::getIsSend, dieOrder.getIsSend());
        }
        if (dieOrder.getCompleteOrder() != null) {
            queryWrapper.eq(DieOrder::getCompleteOrder, dieOrder.getCompleteOrder());
        } else {
            queryWrapper.isNull(DieOrder::getCompleteOrder);
        }

        // 获取分页后的DieOrder列表
        List<DieOrder> dieOrderList = dieOrderMapper.selectPage(pages, queryWrapper).getRecords();

        List<DieOrderVo> dieOrderVoList = dieOrderList.stream().map(item -> {
            DieOrderVo vo = new DieOrderVo();
            BeanUtils.copyProperties(item, vo);
            return vo;
        }).collect(Collectors.toList());

        // 准备返回结果
        DieOrderPageVO orderPageVO = new DieOrderPageVO();

        orderPageVO.setTotal(pages.getTotal());
        orderPageVO.setDieOrderList(dieOrderVoList);
        return Result.success("查询成功", orderPageVO);
    }

    // 模拟的将ID转换为名称的方法
    private Map<String, String> getNamesByIds(Set<String> ids) {
        Map<String, String> idToNameMap = new HashMap<>();
        if (ids.size() != 0) {
            // 这个方法应该查询数据库或其他数据源以获取对应名称
            List<User> userList = userMapper.selectBatchByIdWithDelete(ids);
            // 这里我们用一个模拟的映射表来演示
            for (User user : userList) {
                idToNameMap.put(user.getId(), user.getNickName()); // 用实际的名称查找逻辑替换
            }
        }
        return idToNameMap;
    }

    // 将ID字符串替换为名称字符串的方法
    private String replaceIdsWithNames(String ids, Map<String, String> idToNameMap) {
        if (ids == null || ids.isEmpty()) {
            return ids;
        }
        return Arrays.stream(ids.split(","))
                .map(id -> idToNameMap.getOrDefault(id, id))
                .collect(Collectors.joining(","));
    }

    /**
     * 修改用户订单状态
     * customId 订单id
     * 
     * @param type
     * @param status
     * @return
     */
    @SuppressWarnings("null")
    @Override
    public Result updateOrderStatus(DieOrderDto dieOrder) {
        if (dieOrder.getId() == null && (dieOrder.getStOneB() == null && dieOrder.getStTwoB() == null &&
                dieOrder.getStThreeB() == null && dieOrder.getStFourB() == null &&
                dieOrder.getStFiveB() == null && dieOrder.getSurPriceB() == null)) {
            return Result.error("缺少参数");
        }
        DieOrder order = dieOrderMapper.selectById(dieOrder.getId());
        if (dieOrderMapper.selectById(dieOrder.getId()) == null) {
            return Result.error("订单不存在");
        }
        String userId = StpUtil.getLoginId().toString();
        String[] listStrings = null;
        if (dieOrder.getStOneB() != null) {
            if (order.getStOne() == null) {
                order.setStOne("");
            }
            Set<String> set = new HashSet<>(Arrays.asList(order.getStOne().split(",")));
            set.remove("");
            if (dieOrder.getStOneB()) {
                set.add(userId);
            } else {
                set.remove(userId);
            }
            order.setStOne(String.join(",", set));
            listStrings = set.toArray(new String[set.size()]);
        }
        if (dieOrder.getStTwoB() != null) {
            if (order.getStTwo() == null) {
                order.setStTwo("");
            }
            Set<String> set = new HashSet<>(Arrays.asList(order.getStTwo().split(",")));
            set.remove("");
            if (dieOrder.getStTwoB()) {
                set.add(userId);
            } else {
                set.remove(userId);
            }
            order.setStTwo(String.join(",", set));
            listStrings = set.toArray(new String[set.size()]);
        }
        if (dieOrder.getStThreeB() != null) {
            if (order.getStThree() == null) {
                order.setStThree("");
            }
            Set<String> set = new HashSet<>(Arrays.asList(order.getStThree().split(",")));
            set.remove("");
            if (dieOrder.getStThreeB()) {
                set.add(userId);
            } else {
                set.remove(userId);
            }
            order.setStThree(String.join(",", set));
            listStrings = set.toArray(new String[set.size()]);
        }
        if (dieOrder.getStFourB() != null) {
            if (order.getStFour() == null) {
                order.setStFour("");
            }
            Set<String> set = new HashSet<>(Arrays.asList(order.getStFour().split(",")));
            set.remove("");
            if (dieOrder.getStFourB()) {
                set.add(userId);
            } else {
                set.remove(userId);
            }
            order.setStFour(String.join(",", set));
            listStrings = set.toArray(new String[set.size()]);
        }
        if (dieOrder.getStFiveB() != null) {
            if (order.getStFive() == null) {
                order.setStFive("");
            }
            Set<String> set = new HashSet<>(Arrays.asList(order.getStFive().split(",")));
            set.remove("");
            if (dieOrder.getStFiveB()) {
                set.add(userId);
            } else {
                set.remove(userId);
            }
            order.setStFive(String.join(",", set));
            listStrings = set.toArray(new String[set.size()]);
        }
        if (dieOrder.getSurPriceB() != null) {
            if (order.getSurPrice() == null) {
                order.setSurPrice("");
            }
            Set<String> set = new HashSet<>(Arrays.asList(order.getSurPrice().split(",")));
            set.remove("");
            if (dieOrder.getSurPriceB()) {
                set.add(userId);
            } else {
                set.remove(userId);
            }
            order.setSurPrice(String.join(",", set));
            listStrings = set.toArray(new String[set.size()]);
        }
        dieOrderMapper.updateById(order);

        return Result.success("修改成功");
    }


    @Override
    public Result getOrderListByUser(LocalDate startDate, LocalDate endDate, Integer select, String name, Integer page,
            Integer size) {
        // 检查日期参数
        if (startDate == null || endDate == null) {
            return Result.error("开始日期和结束日期不能为空");
        }

        // 先查询所有符合条件的数据
        MPJLambdaQueryWrapper<DieOrder> queryWrapper = new MPJLambdaQueryWrapper<>();
        queryWrapper.selectAll(DieOrder.class).selectAll(DieCustom.class, "t1")
                .leftJoin(" die_custom t1 on t1.id = t.name_id");
        queryWrapper.isNotNull(DieOrder::getCompleteOrder)
                .ge(DieOrder::getCreateTime, startDate)
                .lt(DieOrder::getCreateTime, endDate.plusDays(1));

        List<String> customIdList = dieCustomMapper
                .selectList(new LambdaQueryWrapper<DieCustom>().like(DieCustom::getCustomName, name)).stream()
                .map(DieCustom::getId).collect(Collectors.toList());
        if (customIdList.size() != 0) {
            queryWrapper.and(eq -> eq.in(DieOrder::getNameId, customIdList).or().like(DieOrder::getProductName, name)
                    .or().like(DieOrder::getVersionNumber, name));
        } else {
            queryWrapper.and(eq -> eq.like(DieOrder::getProductName, name).or().like(DieOrder::getVersionNumber, name));
        }

        // 先获取所有数据
        List<DieOrderJoin> allDieOrderList = dieOrderMapper.selectJoinList(DieOrderJoin.class, queryWrapper);

        // 排序
        switch (select) {
            case 1:
                allDieOrderList.sort((o1, o2) -> getAllPinyin(o1.getCustomName()).compareTo(getAllPinyin(o2.getCustomName())));
                break;
            case 2:
                allDieOrderList.sort((o1, o2) -> getAllPinyin(o2.getCustomName()).compareTo(getAllPinyin(o1.getCustomName())));
                break;
            case 3:
                allDieOrderList.sort((o1, o2) -> Collator.getInstance(Locale.CHINA)
                        .compare(o1.getVersionNumber(), o2.getVersionNumber()));
                break;
            case 4:
                allDieOrderList.sort((o1, o2) -> Collator.getInstance(Locale.CHINA)
                        .compare(o2.getVersionNumber(), o1.getVersionNumber()));
                break;
        }

        // 手动分页
        long total = allDieOrderList.size();
        int start = (page - 1) * size;
        int end = Math.min(start + size, allDieOrderList.size());
        List<DieOrderJoin> dieOrderList = allDieOrderList.subList(start, end);

        // 转换为VO
        List<DieOrderVo> dieOrderVoList = dieOrderList.stream().map(item -> {
            DieOrderVo vo = new DieOrderVo();
            BeanUtils.copyProperties(item, vo);
            return vo;
        }).collect(Collectors.toList());

        // 处理收款信息
        for (DieOrderVo item : dieOrderVoList) {
            if (item.getReceivables() == 1) {
                List<dieOrderReceivables> dieOrderReceivables = dmapper.selectList(null);
                aiku.numericalcontroloa.Model.Entity.dieOrderReceivables die = null;
                for (int i = 0; i < dieOrderReceivables.size(); i++) {
                    if (i == dieOrderReceivables.size() - 1) {
                        die = dieOrderReceivables.get(i);
                    } else {
                        if (dieOrderReceivables.get(i).getDieOrderId() == dieOrderReceivables.get(i + 1).getDieOrderId()) {
                            die = dieOrderReceivables.get(i);
                        }
                    }
                }
                if (dieOrderReceivables.size() > 1) {
                    dmapper.deleteById(dieOrderReceivables.get(1));
                }
                Account account = accountMapper.selectById(die.getDieOrderId());
                if (!ObjectUtils.isEmpty(account)) {
                    String accountName = account.getAccountName();
                    item.setAccountName(accountName);
                }
            } else {
                item.setAccountName(null);
            }
        }

        // 准备返回结果
        DieOrderPageVO orderPageVO = new DieOrderPageVO();
        orderPageVO.setTotal(total);  // 使用实际的总数
        orderPageVO.setDieOrderList(dieOrderVoList);

        return Result.success(orderPageVO);
    }

    @Override
    public Result getAllOrderListByUser(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSX") LocalDate startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSX") LocalDate endDate,
            Integer select,
            String name
    ) {
        // 参数校验
        if (startDate == null || endDate == null) {
            return Result.error("开始日期和结束日期不能为空");
        }

        // 构建查询条件
        MPJLambdaQueryWrapper<DieOrder> queryWrapper = new MPJLambdaQueryWrapper<>();
        queryWrapper.selectAll(DieOrder.class)
                .selectAll(DieCustom.class, "t1")
                .leftJoin(" die_custom t1 on t1.id = t.name_id")
                .isNotNull(DieOrder::getCompleteOrder)
                .ge(DieOrder::getCreateTime, startDate)
                .lt(DieOrder::getCreateTime, endDate.plusDays(1));

        // 处理名称查询条件
        List<String> customIdList = dieCustomMapper
                .selectList(new LambdaQueryWrapper<DieCustom>().like(DieCustom::getCustomName, name))
                .stream()
                .map(DieCustom::getId)
                .collect(Collectors.toList());

        if (!customIdList.isEmpty()) {
            queryWrapper.and(wrapper -> wrapper
                    .in(DieOrder::getNameId, customIdList)
                    .or()
                    .like(DieOrder::getProductName, name)
                    .or()
                    .like(DieOrder::getVersionNumber, name));
        } else {
            queryWrapper.and(wrapper -> wrapper
                    .like(DieOrder::getProductName, name)
                    .or()
                    .like(DieOrder::getVersionNumber, name));
        }

        // 获取全量数据
        List<DieOrderJoin> allDieOrderList = dieOrderMapper.selectJoinList(DieOrderJoin.class, queryWrapper);

        // 排序逻辑
        switch (select) {
            case 1:
                allDieOrderList.sort(Comparator.comparing(o -> getAllPinyin(o.getCustomName())));
                break;
            case 2:
                allDieOrderList.sort((o1, o2) -> getAllPinyin(o2.getCustomName()).compareTo(getAllPinyin(o1.getCustomName())));
                break;
            case 3:
                Collator collator = Collator.getInstance(Locale.CHINA);
                allDieOrderList.sort((o1, o2) -> collator.compare(o1.getVersionNumber(), o2.getVersionNumber()));
                break;
            case 4:
                Collator reverseCollator = Collator.getInstance(Locale.CHINA);
                allDieOrderList.sort((o1, o2) -> reverseCollator.compare(o2.getVersionNumber(), o1.getVersionNumber()));
                break;
        }

        // ========== 收集ID ==========
        // 1. 客户名称ID（nameId）
        Set<String> customIds = allDieOrderList.stream()
                .map(DieOrderJoin::getNameId)
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toSet());

        // 2. 用户ID（特殊字段）
        Set<String> userIds = new HashSet<>();
        List<String> userFields = Arrays.asList("stOne", "stTwo", "stThree", "stFour", "stFive", "stSix", "surPrice");
        allDieOrderList.forEach(order -> {
            userFields.forEach(field -> {
                try {
                    Field f = order.getClass().getDeclaredField(field);
                    f.setAccessible(true);
                    String value = (String) f.get(order);
                    if (StringUtils.isNotBlank(value)) {
                        Arrays.stream(value.split(","))
                                .forEach(userIds::add);
                    }
                } catch (Exception e) {
                    log.error("反射获取字段失败: {}", field, e);
                }
            });
        });

        // ========== 批量查询 ==========
        // 1. 客户名称映射
        Map<String, String> customNameMap = dieCustomMapper.selectList(
                new LambdaQueryWrapper<DieCustom>().in(DieCustom::getId, customIds)
        ).stream().collect(Collectors.toMap(DieCustom::getId, DieCustom::getCustomName));

        // 2. 用户昵称映射
        Map<String, String> userNickNameMap = userIds.isEmpty() ?
                new HashMap<>() :
                userMapper.selectList(new LambdaQueryWrapper<User>().in(User::getId, userIds))
                        .stream()
                        .collect(Collectors.toMap(User::getId, User::getNickName));

        // ========== 转换结果 ==========
        List<Map<String, Object>> result = allDieOrderList.stream().map(item -> {
            Map<String, Object> map = new LinkedHashMap<>();

            // 手动填充基础字段
            map.put("id", item.getId());
            map.put("nameId", item.getNameId());
            map.put("versionNumber", item.getVersionNumber());
            map.put("productName", item.getProductName());
            map.put("price", item.getPrice());
            map.put("isSend", item.getIsSend());
            map.put("deliveryTime", item.getDeliveryTime());
            map.put("stOne", item.getStOne());
            map.put("stTwo", item.getStTwo());
            map.put("stThree", item.getStThree());
            map.put("stFour", item.getStFour());
            map.put("stFive", item.getStFive());
            map.put("stSix", item.getStSix());
            map.put("surPrice", item.getSurPrice());
            map.put("head", item.getHead());
            map.put("triggerSituation", item.getTriggerSituation());
            map.put("deliveryId", item.getDeliveryId());
            map.put("receivables", item.getReceivables());
            map.put("completeOrder", item.getCompleteOrder());
            map.put("createTime", item.getCreateTime());
            map.put("updateTime", item.getUpdateTime());
            map.put("deleted", item.getDeleted());
            map.put("accountName", null);

            // 处理客户名称（nameId对应）
            String nameId = item.getNameId();
            if (StringUtils.isNotBlank(nameId)) {
                map.put("customName", customNameMap.getOrDefault(nameId, nameId));
            }

            // 处理用户昵称字段（仅处理有值的字段）
            userFields.forEach(field -> {
                try {
                    Field f = item.getClass().getDeclaredField(field);
                    f.setAccessible(true);
                    String ids = (String) f.get(item);

                    if (StringUtils.isNotBlank(ids)) {
                        String names = Arrays.stream(ids.split(","))
                                .map(id -> userNickNameMap.getOrDefault(id, "未知用户"))
                                .collect(Collectors.joining(","));
                        map.put(field + "Names", names);
                    }
                    // 空值不添加字段
                } catch (Exception e) {
                    log.error("字段处理失败: {}", field, e);
                }
            });

            // 处理收款信息
            if (map.get("receivables") != null && (Integer) map.get("receivables") == 1) {
                List<dieOrderReceivables> receivables = dmapper.selectList(null);
                dieOrderReceivables latest = !receivables.isEmpty() ?
                        receivables.get(receivables.size() - 1) : null;

                if (receivables.size() > 1) {
                    dmapper.deleteById(receivables.get(0).getId());
                }

                if (latest != null) {
                    Account account = accountMapper.selectById(latest.getDieOrderId());
                    if (account != null) {
                        map.put("accountName", account.getAccountName());
                    }
                }
            }

            return map;
        }).collect(Collectors.toList());

        return Result.success(result);
    }

    /**
     * 根据年份或年月来查询收益排行榜
     * 
     * @param yearOrMonth 格式：yyyy 或 yyyy-MM
     * @return
     */
    @Override
    public Result getIncomeRanking(String yearOrMonth) {
        List<DieBonusinfo> bonusinfoArrayList = null;
        try {
            LambdaQueryWrapper<DieBonusinfo> queryWrapper = new LambdaQueryWrapper<>();

            // 根据传入的参数构建查询条件
            if (!StringUtils.isEmpty(yearOrMonth)) {
                if (yearOrMonth.contains("-")) {
                    // 按年月查询 (yyyy-MM)
                    String[] parts = yearOrMonth.split("-");
                    String year = parts[0];
                    String month = String.format("%02d", Integer.parseInt(parts[1]));
                    queryWrapper.apply("DATE_FORMAT(time, '%Y-%m') = {0}", year + "-" + month);
                } else {
                    // 按年查询 (yyyy)
                    queryWrapper.apply("YEAR(time) = {0}", yearOrMonth);
                }
            }

            // 执行查询
            List<DieBonusinfo> dieBonusinfoList = dieBonusinfoMapper.selectList(queryWrapper);
            if (dieBonusinfoList.isEmpty()) {
                return Result.success(new ArrayList<>());
            }

            // 按用户ID分组并计算分红总额
            Map<String, BigDecimal> userBonusMap = new HashMap<>();
            for (DieBonusinfo bonusinfo : dieBonusinfoList) {
                String userId = bonusinfo.getUserId();
                BigDecimal price = bonusinfo.getPrice();
                if (price != null) {
                    userBonusMap.merge(userId, price, BigDecimal::add);
                }
            }

            // 构建结果列表
            List<Map<String, Object>> resultList = new ArrayList<>();
            for (Map.Entry<String, BigDecimal> entry : userBonusMap.entrySet()) {
                String userId = entry.getKey();
                User user = userMapper.selectById(userId);
                if (user != null) {
                    Map<String, Object> userBonus = new HashMap<>();
                    userBonus.put("userId", userId);  // 返回用户ID
                    userBonus.put("name", user.getNickName());  // 返回用户名称
                    userBonus.put("price", entry.getValue());  // 返回分红金额
                    resultList.add(userBonus);
                }
            }

            // 按分红金额降序排序
            resultList.sort((a, b) -> ((BigDecimal)b.get("price")).compareTo((BigDecimal)a.get("price")));

            return Result.success("获取成功", resultList);
        } catch (Exception e) {
            log.error("查询分红排行榜失败: {}", e.getMessage());
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 查询订单分红
     * 
     * @param customId
     * @return
     */
    @Override
    public Result getOrderCommission(String customId) {
        // 用户用户ID
        String userId = StpUtil.getLoginId().toString();
        LambdaQueryWrapper<DieBonusinfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DieBonusinfo::getCustomId, customId);
        queryWrapper.eq(DieBonusinfo::getUserId, userId);
        List<DieBonusinfo> bonusinfoList = dieBonusinfoMapper.selectList(queryWrapper);
        // 把金额累积
        BigDecimal price = new BigDecimal("0");
        DieOrder order = new DieOrder();
        for (DieBonusinfo bonusinfo : bonusinfoList) {
            price = price.add(bonusinfo.getPrice());
        }
        order.setPrice(price);
        return Result.success(order);
    }

    public String getAllPinyin(String hanzi) {
        // 输出格式设置
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        format.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);

        char[] hanYuArr = hanzi.trim().toCharArray();
        StringBuilder pinYin = new StringBuilder();

        try {
            for (int i = 0, len = hanYuArr.length; i < len; i++) {
                // 匹配是否是汉字
                if (Character.toString(hanYuArr[i]).matches("[\\u4E00-\\u9FA5]+")) {
                    // 如果是多音字，返回多个拼音，这里只取第一个
                    String[] pys = PinyinHelper.toHanyuPinyinStringArray(hanYuArr[i], format);
                    pinYin.append(pys[0]).append(" ");
                } else {
                    pinYin.append(hanYuArr[i]).append(" ");
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
            badHanyuPinyinOutputFormatCombination.printStackTrace();
        }
        return pinYin.toString();
    }

    /**
     * 通过订单名称模糊查询订单信息
     * 
     * @param name
     * @return
     */
    @Override
    public Result getOrderListByLike(String name, Integer type, Integer page, Integer size, LocalDate startDate,
            LocalDate endDate) {
        Page<DieOrderJoin> Page = new Page<>(page, size);
        MPJLambdaQueryWrapper<DieOrder> queryWrapper = new MPJLambdaQueryWrapper<>();
        queryWrapper.selectAll(DieOrder.class).selectAll(DieCustom.class, "t1")
                .leftJoin(" die_custom t1 on t1.id = t.name_id");

        if (!name.equals("")) {
            List<String> customIdList = dieCustomMapper
                    .selectList(new LambdaQueryWrapper<DieCustom>().like(DieCustom::getCustomName, name)).stream()
                    .map(DieCustom::getId).collect(Collectors.toList());
            if (customIdList.size() != 0) {
                queryWrapper.in(DieOrder::getNameId, customIdList).or();
            }
            queryWrapper.like(DieOrder::getProductName, name).or().like(DieOrder::getVersionNumber, name);
        }
        if (startDate != null && endDate != null) {
            queryWrapper.ge(DieOrder::getCreateTime, startDate).lt(DieOrder::getCreateTime, endDate);
        }
        queryWrapper.isNull(DieOrder::getCompleteOrder);
        List<DieOrderJoin> dieOrderList = dieOrderMapper.selectJoinPage(Page, DieOrderJoin.class, queryWrapper)
                .getRecords();
        switch (type) {
            case 1:
                dieOrderList = dieOrderList.stream().sorted(
                        (o1, o2) -> getAllPinyin(o1.getCustomName()).compareTo(getAllPinyin(o2.getCustomName())))
                        .collect(Collectors.toList());
                break;
            case 2:
                dieOrderList = dieOrderList.stream().sorted(
                        (o1, o2) -> getAllPinyin(o2.getCustomName()).compareTo(getAllPinyin(o1.getCustomName())))
                        .collect(Collectors.toList());
                break;
            case 3:
                dieOrderList = dieOrderList.stream().sorted((o1, o2) -> Collator.getInstance(Locale.CHINA)
                        .compare(o1.getVersionNumber(), o2.getVersionNumber())).collect(Collectors.toList());
                break;
            case 4:
                dieOrderList = dieOrderList.stream().sorted((o1, o2) -> Collator.getInstance(Locale.CHINA)
                        .compare(o2.getVersionNumber(), o1.getVersionNumber())).collect(Collectors.toList());
                break;
            case 5:
                dieOrderList = dieOrderList.stream().sorted((o1, o2) -> Collator.getInstance(Locale.CHINA)
                        .compare(o2.getVersionNumber(), o1.getVersionNumber())).collect(Collectors.toList());
                break;
        }

        Map<String, Object> map = new HashMap<>();
        map.put("dieOrderList", dieOrderList);
        map.put("total", Page.getTotal());
        return Result.success(map);
    }

    /**
     * 通过订单名称模糊查询订单信息,查询当前用户自己的信息
     * 
     * @param name
     * @return
     */
    @Override
    public Result getOrderListByLikeAndUser(String name, Integer page,
            Integer size) {

        // 根据CustomId批量查询DieOrder列表
        // List<DieOrder> dieOrderList = dieOrderMapper.selectBatchIds(customIdSet);
        LambdaQueryWrapper<DieOrder> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.like(DieOrder::getVersionNumber, name).or()
                .like(DieOrder::getProductName, name).or()
                .like(DieOrder::getNameId, name);
        List<DieOrder> dieOrderList = dieOrderMapper.selectList(queryWrapper1);
        return Result.success(dieOrderList);
    }

    /**
     *
     * @param name
     * @param day
     * @return
     */
    @Override
    public Result userNameDieOrderInfo(String name, LocalDate stratDate, LocalDate endDate) {
        // 创建分页对象
        LambdaQueryWrapper<DieOrder> queryWrapper = new LambdaQueryWrapper<>();
        // 通过传入的天数,来查询天数内的数据,获取一个当前时间,再使用传入的天数乘以一天的时间,就可以得到时间范围
        queryWrapper.eq(DieOrder::getNameId, name);

        if (stratDate != null || endDate != null) {
            queryWrapper.ge(DieOrder::getCreateTime, stratDate).le(DieOrder::getCreateTime, endDate);
        }

        // 获取总记录数
        Long count = dieOrderMapper.selectCount(queryWrapper);

        // 获取分页后的DieOrder列表并按version_number倒序排序
        List<DieOrder> dieOrderList = dieOrderMapper.selectList(queryWrapper);
        dieOrderList = dieOrderList.stream()
                .sorted((o1, o2) -> {
                    String v1 = o1.getVersionNumber() != null ? o1.getVersionNumber() : "";
                    String v2 = o2.getVersionNumber() != null ? o2.getVersionNumber() : "";
                    return v2.compareTo(v1);  // 倒序排序
                })
                .collect(Collectors.toList());

        // 从DieOrder列表中提取所有相关的ID，并去重
        Set<String> allIds = new HashSet<>();
        if (dieOrderList != null) { // 检查 dieOrderList 是否为空
            dieOrderList.forEach(order -> {
                if (order != null) { // 检查 order 是否为空
                    if (order.getStOne() != null) {
                        allIds.addAll(Arrays.asList(order.getStOne().split(",")));
                    }
                    if (order.getStTwo() != null) {
                        allIds.addAll(Arrays.asList(order.getStTwo().split(",")));
                    }
                    if (order.getStThree() != null) {
                        allIds.addAll(Arrays.asList(order.getStThree().split(",")));
                    }
                    if (order.getStFour() != null) {
                        allIds.addAll(Arrays.asList(order.getStFour().split(",")));
                    }
                    if (order.getStFive() != null) {
                        allIds.addAll(Arrays.asList(order.getStFive().split(",")));
                    }
                    if (order.getSurPrice() != null) {
                        allIds.addAll(Arrays.asList(order.getSurPrice().split(",")));
                    }
                }
            });
        }

        // 查询ID对应的昵称 (模拟实现)
        if (!allIds.isEmpty()) {
            Map<String, String> idToNameMap = getNamesByIds(allIds);

            // 将DieOrder中的ID替换为昵称
            dieOrderList.forEach(order -> {
                order.setStOne(replaceIdsWithNames(order.getStOne(), idToNameMap));
                order.setStTwo(replaceIdsWithNames(order.getStTwo(), idToNameMap));
                order.setStThree(replaceIdsWithNames(order.getStThree(), idToNameMap));
                order.setStFour(replaceIdsWithNames(order.getStFour(), idToNameMap));
                order.setStFive(replaceIdsWithNames(order.getStFive(), idToNameMap));
                order.setSurPrice(replaceIdsWithNames(order.getSurPrice(), idToNameMap));

            });
        }

        List<DieOrderVo> dieOrderVoList = dieOrderList.stream().map(item -> {
            DieOrderVo vo = new DieOrderVo();
            if (ObjectUtils.isEmpty(item.getPrice())) {
                item.setPrice(new BigDecimal(0.00));
            }
            BeanUtils.copyProperties(item, vo);
            return vo;
        }).collect(Collectors.toList());

        // 准备返回结果
        DieOrderPageVO orderPageVO = new DieOrderPageVO();
        orderPageVO.setTotal(count);
        orderPageVO.setDieOrderList(dieOrderVoList);

        return Result.success(orderPageVO);
    }

    // 检测数组是否为空
    private boolean isArrayEmpty(String[] array) {
        if (array == null || array.length == 0) {
            return true;
        }
        for (String str : array) {
            if (str != null && !str.trim().isEmpty()) {
                return false;
            }
        }
        return true;
    }

    @Override
    public Result successOrders(String id) {
        if (id == null) {
            return Result.error("缺少id");
        }
        DieOrder dieOrder = dieOrderMapper.selectById(id);
        if (dieOrder == null) {
            return Result.error("无此订单");
        }
        if (dieOrder.getCompleteOrder() != null) {
            return Result.error("此订单已经完成");
        }
        String userid = StpUtil.getLoginId().toString();
        DieOrder order = new DieOrder();
        order.setId(id);
        order.setCompleteOrder(userid);
        if (dieOrderMapper.updateById(order) == 1) {
            // 公式等于,100元 零件人数不一样,分红也不一样,比如这个产品100元绘图部这次是4个人参加,
            // 然后绘图部分红是总额的10%,那么这个绘图分红就是10元,分给4个人平分,人越多,分的越少
            // 公式是:分红=总额*分红比例/人数
            // 那我我现在有绘图,装刀,装线,切割,打包,这5个部门,每个部门的分红比例是不一样的,第一个部门是10%,第二个部门是5%,第三个部门是5%,第四个部门是10%,第五个部门是15%
            // 那么我现在要计算这个订单的分红,我就要把这个订单的总额拿到,然后分别乘以这5个部门的分红比例,然后除以这5个部门的人数,我要计算出每位员工的分红是多少
            DieBonus dieBonus = dieBonusMapper.selectById("1");
            if (dieOrder.getStOne() != null && !dieOrder.getStOne().equals("")) {
                String[] ids = dieOrder.getStOne().split(",");
                for (String item : ids) {
                    DieBonusinfo dieBonusinfo = new DieBonusinfo();
                    dieBonusinfo.setUserId(item);
                    if (!ObjectUtils.isEmpty(dieOrder.getPrice())) {
                        dieBonusinfo.setPrice(
                                dieOrder.getPrice().multiply(dieBonus.getOnePrice().divide(new BigDecimal("100")))
                                        .divide(BigDecimal.valueOf(ids.length)));
                    }
                    dieBonusinfo.setType("1");
                    dieBonusinfo.setCustomId(dieOrder.getId());
                    dieBonusinfoMapper.insert(dieBonusinfo);
                }
            }
            if (dieOrder.getStTwo() != null && !dieOrder.getStTwo().equals("")) {
                String[] ids = dieOrder.getStTwo().split(",");
                for (String item : ids) {
                    DieBonusinfo dieBonusinfo = new DieBonusinfo();
                    dieBonusinfo.setUserId(item);
                    dieBonusinfo.setPrice(
                            dieOrder.getPrice().multiply(dieBonus.getTwoPrice().divide(new BigDecimal("100")))
                                    .divide(BigDecimal.valueOf(ids.length)));
                    dieBonusinfo.setType("2");
                    dieBonusinfo.setCustomId(dieOrder.getId());
                    dieBonusinfoMapper.insert(dieBonusinfo);
                }
            }
            if (dieOrder.getStThree() != null && !dieOrder.getStThree().equals("")) {
                String[] ids = dieOrder.getStThree().split(",");
                for (String item : ids) {
                    DieBonusinfo dieBonusinfo = new DieBonusinfo();
                    dieBonusinfo.setUserId(item);
                    dieBonusinfo.setPrice(
                            dieOrder.getPrice().multiply(dieBonus.getThreePrice().divide(new BigDecimal("100")))
                                    .divide(BigDecimal.valueOf(ids.length)));
                    dieBonusinfo.setType("3");
                    dieBonusinfo.setCustomId(dieOrder.getId());
                    dieBonusinfoMapper.insert(dieBonusinfo);
                }
            }
            if (dieOrder.getStFour() != null && !dieOrder.getStFour().equals("")) {
                String[] ids = dieOrder.getStFour().split(",");
                for (String item : ids) {
                    DieBonusinfo dieBonusinfo = new DieBonusinfo();
                    dieBonusinfo.setUserId(item);
                    dieBonusinfo.setPrice(
                            dieOrder.getPrice().multiply(dieBonus.getFourPrice().divide(new BigDecimal("100")))
                                    .divide(BigDecimal.valueOf(ids.length)));
                    dieBonusinfo.setType("4");
                    dieBonusinfo.setCustomId(dieOrder.getId());
                    dieBonusinfoMapper.insert(dieBonusinfo);
                }
            }
            if (dieOrder.getStFive() != null && !dieOrder.getStFive().equals("")) {
                String[] ids = dieOrder.getStFive().split(",");
                for (String item : ids) {
                    DieBonusinfo dieBonusinfo = new DieBonusinfo();
                    dieBonusinfo.setUserId(item);
                    dieBonusinfo.setPrice(
                            dieOrder.getPrice().multiply(dieBonus.getFive().divide(new BigDecimal("100")))
                                    .divide(BigDecimal.valueOf(ids.length)));
                    dieBonusinfo.setType("5");
                    dieBonusinfo.setCustomId(dieOrder.getId());
                    dieBonusinfoMapper.insert(dieBonusinfo);
                }
            }
            if (dieOrder.getSurPrice() != null && !dieOrder.getSurPrice().equals("")) {
                String[] ids = dieOrder.getSurPrice().split(",");
                for (String item : ids) {
                    DieBonusinfo dieBonusinfo = new DieBonusinfo();
                    dieBonusinfo.setUserId(item);
                    dieBonusinfo.setPrice(
                            dieOrder.getPrice().multiply(dieBonus.getSix().divide(new BigDecimal("100")))
                                    .divide(BigDecimal.valueOf(ids.length)));
                    dieBonusinfo.setType("6");
                    dieBonusinfo.setCustomId(dieOrder.getId());
                    dieBonusinfoMapper.insert(dieBonusinfo);
                }
            }
            return Result.success("订单已确认完成");
        } else {
            return Result.error("确认异常");
        }
    }

    @Override
    public Result deleteOrders(String id) {
        if (id == null) {
            return Result.error("请输入id");
        }
        String userid = StpUtil.getLoginId().toString();
        if (!userMapper.selectById(userid).getRoleId().equals("1")) {
            return Result.error("权限不足");
        }
        if (dieOrderMapper.selectById(id) != null) {
            if (dieOrderMapper.deleteById(id) == 1) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } else {
            return Result.error("订单不存在");
        }
    }

    @Override
    public Result setReceivables(String id, String accountId) {
        if (id == null) {
            return Result.error("请输入id");
        }
        DieOrder order = dieOrderMapper.selectById(id);
        if (order != null) {
            order.setReceivables(1);
            if (dieOrderMapper.updateById(order) == 1) {
                dieOrderReceivables d = new dieOrderReceivables();
                d.setAccountId(accountId);
                d.setDieOrderId(id);
                d.setDeleted(0);
                dmapper.insert(d);

                Account account = accountMapper.selectById(accountId);
                if (!ObjectUtils.isEmpty(account.getBalance()) && !ObjectUtils.isEmpty(order.getPrice())) {
                    account.setBalance(account.getBalance().add(order.getPrice()));
                }
                accountMapper.updateById(account);

                return Result.success("收款成功");
            } else {
                return Result.error("收款失败");
            }
        } else {
            return Result.error("订单不存在");
        }
    }

    @Override
    public Result getStatistics(String yearOrMonth) {
        try {
            String year;
            String month = null;
            
            // 处理输入参数
            if (StringUtils.isEmpty(yearOrMonth)) {
                // 如果没有传入参数，使用当前年月
                LocalDate now = LocalDate.now();
                year = String.valueOf(now.getYear());
                month = String.format("%02d", now.getMonthValue());
            } else if (yearOrMonth.contains("-")) {
                // 格式为 yyyy-MM
                String[] parts = yearOrMonth.split("-");
                year = parts[0];
                // 确保月份是两位数
                month = String.format("%02d", Integer.parseInt(parts[1]));
            } else {
                // 仅年份
                year = yearOrMonth;
            }

            // 构建查询条件
            LambdaQueryWrapper<DieOrder> queryWrapper = new LambdaQueryWrapper<>();
            if (month != null) {
                // 查询特定年月，打印SQL帮助调试
                String dateFormat = year + "-" + month;
                System.out.println("查询的年月格式: " + dateFormat);
                queryWrapper.apply("DATE_FORMAT(create_time, '%Y-%m') = {0}", dateFormat);
            } else {
                // 查询整年
                queryWrapper.apply("YEAR(create_time) = {0}", year);
            }

            // 执行查询并打印结果数量
            List<DieOrder> dieOrders = dieOrderMapper.selectList(queryWrapper);
            System.out.println("查询到的订单数量: " + dieOrders.size());
            
            // 按客户ID统计金额和订单数量
            Map<String, Double> amountByNameId = new HashMap<>();
            Map<String, Integer> orderCountByNameId = new HashMap<>();  // 新增：统计订单数量
            
            for (DieOrder order : dieOrders) {
                String nameId = order.getNameId();
                BigDecimal price = order.getPrice();
                if (price != null) {
                    // 统计金额
                    amountByNameId.merge(nameId, price.doubleValue(), Double::sum);
                    // 统计订单数量
                    orderCountByNameId.merge(nameId, 1, Integer::sum);
                }
            }

            // 构建返回结果
            List<DieOrderStatisticsVo> resultList = new ArrayList<>();
            for (Map.Entry<String, Double> entry : amountByNameId.entrySet()) {
                DieCustom dieCustom = dieCustomMapper.selectById(entry.getKey());
                if (dieCustom != null) {
                    DieOrderStatisticsVo vo = new DieOrderStatisticsVo();
                    vo.setName(dieCustom.getCustomName());
                    vo.setPrice(entry.getValue());
                    vo.setOrderCount(orderCountByNameId.get(entry.getKey()));  // 设置订单数量
                    resultList.add(vo);
                }
            }

            return Result.success("获取成功", resultList);
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    @Override
    public Result updateRoot(DieOrder dieOrder) {
        if (dieOrder.getId() == null || dieOrder.getNameId() == null || dieOrder.getVersionNumber() == null
                || dieOrder.getProductName() == null || dieOrder.getPrice() == null) {
            return Result.error("缺少参数");
        }
        String userid = StpUtil.getLoginId().toString();

        if (!userMapper.selectById(userid).getRoleId().equals("1")) {
            return Result.error("订单已完成，修改权限不足");
        }
        log.info("通过客户名称查询客户的name_id: {}", dieOrder.getNameId());
        QueryWrapper<DieCustom> dieCustomQueryWrapper = new QueryWrapper<>();
        dieCustomQueryWrapper.eq("custom_name", dieOrder.getNameId());
        try {
            DieCustom dieCustom = dieCustomMapper.selectOne(dieCustomQueryWrapper);
            if (ObjectUtils.isEmpty(dieCustom)) {
                return Result.error("客户不存在");
            }
            dieOrder.setNameId(dieCustom.getId());
        } catch (Exception e) {
            return Result.error("客户存在多个");
        }
        if (dieOrderMapper.updateById(dieOrder) == 1) {
            LambdaQueryWrapper<DieBonusinfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DieBonusinfo::getCustomId, dieOrder.getId());
            dieBonusinfoMapper.delete(queryWrapper);

            dieOrder = dieOrderMapper.selectById(dieOrder.getId());
            DieBonus dieBonus = dieBonusMapper.selectById("1");
            if (dieOrder.getStOne() != null && !dieOrder.getStOne().equals("")) {
                String[] ids = dieOrder.getStOne().split(",");
                for (String item : ids) {
                    DieBonusinfo dieBonusinfo = new DieBonusinfo();
                    dieBonusinfo.setUserId(item);
                    dieBonusinfo.setPrice(
                            dieOrder.getPrice().multiply(dieBonus.getOnePrice().divide(new BigDecimal("100")))
                                    .divide(BigDecimal.valueOf(ids.length)));
                    dieBonusinfo.setType("1");
                    dieBonusinfo.setCustomId(dieOrder.getId());
                    dieBonusinfoMapper.insert(dieBonusinfo);
                }
            }
            if (dieOrder.getStTwo() != null && !dieOrder.getStTwo().equals("")) {
                String[] ids = dieOrder.getStTwo().split(",");
                for (String item : ids) {
                    DieBonusinfo dieBonusinfo = new DieBonusinfo();
                    dieBonusinfo.setUserId(item);
                    dieBonusinfo.setPrice(
                            dieOrder.getPrice().multiply(dieBonus.getTwoPrice().divide(new BigDecimal("100")))
                                    .divide(BigDecimal.valueOf(ids.length)));
                    dieBonusinfo.setType("2");
                    dieBonusinfo.setCustomId(dieOrder.getId());
                    dieBonusinfoMapper.insert(dieBonusinfo);
                }
            }
            if (dieOrder.getStThree() != null && !dieOrder.getStThree().equals("")) {
                String[] ids = dieOrder.getStThree().split(",");
                for (String item : ids) {
                    DieBonusinfo dieBonusinfo = new DieBonusinfo();
                    dieBonusinfo.setUserId(item);
                    dieBonusinfo.setPrice(
                            dieOrder.getPrice().multiply(dieBonus.getThreePrice().divide(new BigDecimal("100")))
                            .divide(BigDecimal.valueOf(ids.length)));
                    dieBonusinfo.setType("3");
                    dieBonusinfo.setCustomId(dieOrder.getId());
                    dieBonusinfoMapper.insert(dieBonusinfo);
                }
            }
            if (dieOrder.getStFour() != null && !dieOrder.getStFour().equals("")) {
                String[] ids = dieOrder.getStFour().split(",");
                for (String item : ids) {
                    DieBonusinfo dieBonusinfo = new DieBonusinfo();
                    dieBonusinfo.setUserId(item);
                    dieBonusinfo.setPrice(
                            dieOrder.getPrice().multiply(dieBonus.getFourPrice().divide(new BigDecimal("100")))
                            .divide(BigDecimal.valueOf(ids.length)));
                    dieBonusinfo.setType("4");
                    dieBonusinfo.setCustomId(dieOrder.getId());
                    dieBonusinfoMapper.insert(dieBonusinfo);
                }
            }
            if (dieOrder.getStFive() != null && !dieOrder.getStFive().equals("")) {
                String[] ids = dieOrder.getStFive().split(",");
                for (String item : ids) {
                    DieBonusinfo dieBonusinfo = new DieBonusinfo();
                    dieBonusinfo.setUserId(item);
                    dieBonusinfo.setPrice(
                            dieOrder.getPrice().multiply(dieBonus.getFive().divide(new BigDecimal("100")))
                            .divide(BigDecimal.valueOf(ids.length)));
                    dieBonusinfo.setType("5");
                    dieBonusinfo.setCustomId(dieOrder.getId());
                    dieBonusinfoMapper.insert(dieBonusinfo);
                }
            }
            if (dieOrder.getStSix() != null && !dieOrder.getStSix().equals("")) {
                String[] ids = dieOrder.getStSix().split(",");
                for (String item : ids) {
                    DieBonusinfo dieBonusinfo = new DieBonusinfo();
                    dieBonusinfo.setUserId(item);
                    dieBonusinfo.setPrice(
                            dieOrder.getPrice().multiply(dieBonus.getSix().divide(new BigDecimal("100")))
                            .divide(BigDecimal.valueOf(ids.length)));
                    dieBonusinfo.setType("7");
                    dieBonusinfo.setCustomId(dieOrder.getId());
                    dieBonusinfoMapper.insert(dieBonusinfo);
                }
            }
            if (dieOrder.getSurPrice() != null && !dieOrder.getSurPrice().equals("")) {
                String[] ids = dieOrder.getSurPrice().split(",");
                for (String item : ids) {
                    DieBonusinfo dieBonusinfo = new DieBonusinfo();
                    dieBonusinfo.setUserId(item);
                    dieBonusinfo.setPrice(
                            dieOrder.getPrice().multiply(dieBonus.getSix().divide(new BigDecimal("100")))
                                    .divide(BigDecimal.valueOf(ids.length)));
                    dieBonusinfo.setType("6");
                    dieBonusinfo.setCustomId(dieOrder.getId());
                    dieBonusinfoMapper.insert(dieBonusinfo);
                }
            }

            return Result.success("修改成功");
        } else {
            return Result.error("修改失败");
        }
    }
}
